//
//  HTTextEditor.swift
//  MagaCore
//
//  Created by MrMessy on 2023/6/1.
//

import SwiftUI

struct HTTextEditor: UIViewRepresentable {
  @Binding var var_text: String
  var var_backgroundColor: Color

  func makeUIView(context: Context) -> UITextView {
    let var_textView = UITextView()
    var_textView.backgroundColor = UIColor(var_backgroundColor)
    var_textView.text = var_text
    var_textView.delegate = context.coordinator
    var_textView.textColor = UIColor.black
    return var_textView
  }

  func updateUIView(_ uiView: UITextView, context: Context) {
    if uiView.text != var_text {
      uiView.text = var_text
    }
    if uiView.backgroundColor != UIColor(var_backgroundColor) {
      uiView.backgroundColor = UIColor(var_backgroundColor)
    }
  }

  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

  class Coordinator: NSObject, UITextViewDelegate {
    var parent: HTTextEditor

    init(_ parent: HTTextEditor) {
      self.parent = parent
    }

    func textViewDidChange(_ textView: UITextView) {
      parent.var_text = textView.text
    }
  }
}
